package com.zdkj.subway.stm.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.constant.CommonConstants;
import com.zdkj.common.core.util.R;
import com.zdkj.common.data.mybatis.wrapper.CustomQueryWrapper;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.stm.constant.StmConstans;
import com.zdkj.subway.stm.constant.StmTableCommon;
import com.zdkj.subway.stm.dto.out.SwStInputPassengerWorkOtherDTO;
import com.zdkj.subway.stm.entity.SwStInputPassengerWorkOther;
import com.zdkj.subway.stm.entity.SwStmStationDataEntryLog;
import com.zdkj.subway.stm.mapper.SwStInputPassengerWorkOtherMapper;
import com.zdkj.subway.stm.service.SwStInputPassengerWorkOtherService;
import com.zdkj.subway.stm.service.SwStmStationDataEntryLogService;
import com.zdkj.subway.stm.util.BeanPropertyUtils;
import com.zdkj.subway.stm.util.BeanUtilsStm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 其他相关数据录入
 *
 * @author cuilei
 * @date 2020-05-25 13:38:16
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/swstinputpassengerworkother")
@Api(value = "swstinputpassengerworkother", tags = "其他相关数据录入管理")
public class SwStInputPassengerWorkOtherController {

    private final SwStInputPassengerWorkOtherService swStInputPassengerWorkOtherService;

    private final SwStmStationDataEntryLogService swStmStationDataEntryLogService;
    @Resource
    private SwStInputPassengerWorkOtherMapper swStInputPassengerWorkOtherMapper;

    /**
     * 分页查询
     *
     * @param page                        分页对象
     * @param swStInputPassengerWorkOther 其他相关数据录入
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getSwStInputPassengerWorkOtherPage(Page page, SwStInputPassengerWorkOther swStInputPassengerWorkOther) {
        //LambdaQueryWrapper<SwStInputPassengerWorkOther> queryWrappers = Wrappers.query(swStInputPassengerWorkOther).lambda();
        //QueryWrapper<SwStInputPassengerWorkOther> queryWrappers = Wrappers.query(swStInputPassengerWorkOther);
		String conductorJobNo = swStInputPassengerWorkOther.getConductorCode();
		swStInputPassengerWorkOther.setConductorCode(null);
		swStInputPassengerWorkOther.setConductorName(null);

        QueryWrapper<SwStInputPassengerWorkOther> queryWrappers = Wrappers.query(swStInputPassengerWorkOther);
        String dateCondition = swStInputPassengerWorkOther.getInputTimeDTO();
        if(StringUtils.isNotEmpty(swStInputPassengerWorkOther.getSourceQueryFlag()) && StringUtils.isNotEmpty(conductorJobNo)){
            queryWrappers.lambda().eq(SwStInputPassengerWorkOther::getConductorCode,conductorJobNo);//报表路径跳转
        }
        if(StringUtils.isEmpty(swStInputPassengerWorkOther.getSourceQueryFlag()) && StringUtils.isNotEmpty(conductorJobNo)){
            queryWrappers.lambda().like(SwStInputPassengerWorkOther::getConductorCode,conductorJobNo);//售票员工号模糊匹配
        }
        if (StringUtils.isNotBlank(dateCondition)) {
            queryWrappers.lambda().likeRight(SwStInputPassengerWorkOther::getInputTime, dateCondition);
            return R.ok(swStInputPassengerWorkOtherService.page(page, queryWrappers));
        }
        queryWrappers.orderByDesc("INPUT_TIME");
        if (!SecurityUtils.getUser().getBelongToLine()) {
            queryWrappers.lambda().eq(SwStInputPassengerWorkOther::getLineCode, SecurityUtils.getUser().getLineCode());
            queryWrappers.lambda().eq(SwStInputPassengerWorkOther::getStationCode, SecurityUtils.getUser().getStationCode());
            return R.ok(swStInputPassengerWorkOtherService.page(page, queryWrappers));
        }
        return R.ok(swStInputPassengerWorkOtherService.page(page, queryWrappers));
    }

    @RequestMapping("/getInputPassengerWorkOther")
    public R getInputPassengerWorkOther(@RequestParam Map<String,String> param){
        List<Map<String, Object>> swStInputPassengerWorkOther = swStInputPassengerWorkOtherMapper.getInputPassengerWorkOther(param);
        return R.ok(swStInputPassengerWorkOther);
    }

    /**
     * 通过id查询其他相关数据录入
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swStInputPassengerWorkOtherService.getById(id));
    }

    /**
     * 新增其他相关数据录入
     *
     * @param swStInputPassengerWorkOther 其他相关数据录入
     * @return R
     */
    @ApiOperation(value = "新增其他相关数据录入", notes = "新增其他相关数据录入")
    @SysLog("新增其他相关数据录入")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('stm_sw_st_input_passenger_work_other_add')")
    public R save(@RequestBody SwStInputPassengerWorkOther swStInputPassengerWorkOther) {
        SwStInputPassengerWorkOther defaultObj = ObjectUtils.getDefaultObj(SwStInputPassengerWorkOther.class);
        BeanUtils.copyProperties(swStInputPassengerWorkOther, defaultObj,
                BeanPropertyUtils.getNullAndEmptyPropertyNames(swStInputPassengerWorkOther));

        return R.ok(swStInputPassengerWorkOtherService.save(defaultObj));
    }

    /**
     * 修改其他相关数据录入
     *
     * @param swStInputPassengerWorkOther 其他相关数据录入
     * @return R
     */
    @ApiOperation(value = "修改其他相关数据录入", notes = "修改其他相关数据录入")
    @SysLog("修改其他相关数据录入")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('stm_sw_st_input_passenger_work_other_edit')")
    @Transactional(rollbackFor = Exception.class)
    public R updateById(@RequestBody SwStInputPassengerWorkOther swStInputPassengerWorkOther) {
        SwStInputPassengerWorkOther inputPassengerWorkOther = swStInputPassengerWorkOtherService.getById(swStInputPassengerWorkOther.getId());
        if(ObjectUtil.isNotEmpty(inputPassengerWorkOther)){
            String submitStatus = inputPassengerWorkOther.getSubmitStatus();
            if("1".equals(submitStatus)){
                return R.failed(StmConstans.failedEdit);
            }
        }
        PigxUser user = SecurityUtils.getUser();
        SwStInputPassengerWorkOther workOther = swStInputPassengerWorkOtherService.getById(swStInputPassengerWorkOther.getId());
        if("1".equals(workOther.getReportModifyStatus()) && workOther != null){
            workOther.setEntryUpdateJobNo(user.getUserCode());
            workOther.setEntryUpdateJobName(user.getNikeName());
            workOther.setEntryUpdateTime(new Date());

            SwStmStationDataEntryLog swStmStationDataEntryLog = new SwStmStationDataEntryLog();
            swStmStationDataEntryLog.setRelationId(workOther.getId());
            swStmStationDataEntryLog.setLogTableName(StmTableCommon.SW_ST_INPUT_PASSENGER_WORK_OTHER);
            swStmStationDataEntryLog.setLogInfo(JSONObject.toJSONString(workOther));
            swStmStationDataEntryLog.setUpdateJobNo(user.getUserCode());
            swStmStationDataEntryLog.setUpdateJobName(user.getNikeName());
            swStmStationDataEntryLog.setUpdateTime(new Date());
            swStmStationDataEntryLogService.save(swStmStationDataEntryLog);
            if("1".equals(workOther.getIsMerge())){
                swStInputPassengerWorkOther.setConfirmStatus("1");
            }else{
			    swStInputPassengerWorkOther.setConfirmStatus("0");
			}
        }else{
		    swStInputPassengerWorkOther.setConfirmStatus("0");
		}
        //设备操作号去空格
        swStInputPassengerWorkOther.setDeviceOperateNum(BeanUtilsStm.strRemoveBlank(swStInputPassengerWorkOther.getDeviceOperateNum()));
        return R.ok(swStInputPassengerWorkOtherService.updateById(swStInputPassengerWorkOther));
    }

    /**
     * 通过id查询其他相关数据录入历史记录
     *
     * @param  id
     * @return R
     */
    @ApiOperation(value = "通过id查询其他相关数据录入历史记录", notes = "通过id查询其他相关数据录入历史记录")
    @GetMapping("getLogById/{id}")
    public R getLogById(@PathVariable("id") Integer id) {
        List<Object> LogInfoList = new ArrayList<>();
        List<SwStmStationDataEntryLog> swStmStationDataEntryLogs = swStmStationDataEntryLogService
                .getBaseMapper().selectList(Wrappers.<SwStmStationDataEntryLog>lambdaQuery()
                .eq(SwStmStationDataEntryLog::getRelationId, id)
                .eq(SwStmStationDataEntryLog::getLogTableName, StmTableCommon.SW_ST_INPUT_PASSENGER_WORK_OTHER));
        //返回json串
        if(CollectionUtil.isNotEmpty(swStmStationDataEntryLogs)){
            swStmStationDataEntryLogs.stream().forEach(x -> {
                JSONObject jsonObject = JSONObject.parseObject(x.getLogInfo());
                LogInfoList.add(jsonObject);
            });
        }
        //List<String> LogInfoList = swStmStationDataEntryLogs.stream().map(SwStmStationDataEntryLog::getLogInfo).collect(Collectors.toList());
        return R.ok(LogInfoList);
    }

    /**
     * 通过id删除其他相关数据录入
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除其他相关数据录入", notes = "通过id删除其他相关数据录入")
    @SysLog("通过id删除其他相关数据录入")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('stm_sw_st_input_passenger_work_other_del')")
    public R removeById(@PathVariable Integer id) {
        return R.ok(swStInputPassengerWorkOtherService.removeById(id));
    }

    /**
     * 通过id批量删除其他相关数据录入
     *
     * @param idList id
     * @return R
     */
    @ApiOperation(value = "通过id批量删除其他相关数据录入", notes = "通过id批量删除其他相关数据录入")
    @SysLog("通过id批量删除其他相关数据录入")
    @PostMapping("batchDelete")
    @PreAuthorize("@pms.hasPermission('stm_sw_st_input_passenger_work_other_del')")
    public R batchDeleteById(@RequestBody List<Integer> idList) {
        List<Integer> deleteList = new ArrayList<>();
        idList.forEach(id -> {
            SwStInputPassengerWorkOther swStInputPassengerWorkOther = swStInputPassengerWorkOtherService.getById(id);
            if (CommonConstants.SUBMIT.equals(swStInputPassengerWorkOther.getSubmitStatus())) {
                log.info("已提交数据不能删除！");
            } else {
                deleteList.add(id);
            }
        });
        if(CollectionUtil.isEmpty(deleteList)){
            return R.failed(StmConstans.failedDelete);
        }
        return R.ok(swStInputPassengerWorkOtherService.removeByIds(deleteList));
    }

    /**
     * 批量提交其他相关数据录入
     *
     * @param idList
     * @return
     */
    @ApiOperation(value = "批量提交其他相关数据录入", notes = "批量提交其他相关数据录入")
    @SysLog("批量提交其他相关数据录入")
    @PostMapping("/submit")
    @PreAuthorize("@pms.hasPermission('stm_sw_st_input_passenger_work_other_submit')")
    public R submit(@RequestBody List<Integer> idList) {
        List<SwStInputPassengerWorkOther> submitList = new ArrayList<>();
        idList.forEach(id -> {
            SwStInputPassengerWorkOther submitItem = new SwStInputPassengerWorkOther();
            submitItem.setId(id);
            submitItem.setSubmitStatus(CommonConstants.SUBMIT);
            submitList.add(submitItem);
        });
        return R.ok(swStInputPassengerWorkOtherService.updateBatchById(submitList));
    }

    /**
     * 导出其他相关数据录入
     *
     * @param page
     * @param swStInputPassengerWorkOther
     * @param response
     * @return
     */
    @ApiOperation(value = "导出其他相关数据录入", notes = "导出其他相关数据录入")
    @SysLog("导出其他相关数据录入")
    @GetMapping("/export")
    public void exportExcel(Page page, SwStInputPassengerWorkOther swStInputPassengerWorkOther, HttpServletResponse response) {
        List<SwStInputPassengerWorkOtherDTO> exportList = swStInputPassengerWorkOtherService.pageSelect(page,
                new CustomQueryWrapper(SwStInputPassengerWorkOther.class)
                        .addDTO(swStInputPassengerWorkOther).addAlis("a").addDelFlag(Boolean.TRUE).init()).getRecords();
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("其他相关数据录入", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
            EasyExcel.write(response.getOutputStream(), SwStInputPassengerWorkOtherDTO.class).
                    sheet("其他相关数据录入").doWrite(exportList);
        } catch (IOException e) {
            log.info(e.getMessage());
        }
    }
    /**
     * 其他相关数据录入通过被合并的数据ID查询合并之前的记录
     *
     * @param
     * @return R
     */
    @ApiOperation(value = "通过被合并的数据ID查询合并之前的记录", notes = "通过被合并的数据ID查询合并之前的记录")
    @GetMapping("getMergeBeforById/{id}")
    public R getMergeBeforById(@PathVariable("id") Integer id) {
        SwStInputPassengerWorkOther inputPassengerWorkOther = swStInputPassengerWorkOtherService.getById(id);
        if(ObjectUtil.isNotEmpty(inputPassengerWorkOther)){
            String isBeMergedId = inputPassengerWorkOther.getIsBeMergedId();
            String[] split = isBeMergedId.split(",");
            List<SwStInputPassengerWorkOther> list = swStInputPassengerWorkOtherMapper.getList(split);
            return R.ok(list);
        }else {
            return R.failed("无合并数据！");
        }
    }
}
